/*******************************************************************************
 * Copyright (c) 2012, 2013 XML-Print Project.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     XML-Print Project - initial API and implementation
 ******************************************************************************/
package info.xmlprint.ui.format;

import java.util.ArrayList;

import info.xmlprint.core.format.Format;
import info.xmlprint.core.project.PrintProject;
import info.xmlprint.ui.message.GuiMessages;
import info.xmlprint.ui.widgets.IObserverControl;
import info.xmlprint.ui.widgets.ISubjectControl;
import info.xmlprint.util.FileUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

public class FormatSetup implements ISubjectControl {
	// Zeichenformat
	private FontComposite fontComp;

	// Footnote format
	private FootnoteComposite footnoteComp;

	private Format format;

	// Composite unten
	private Button inlineRadio, blockRadio, footnoteRadio;

	// Language
	private LanguageComposite languageComp;

	private java.util.List<IObserverControl> observerList = new ArrayList<IObserverControl>();

	// Field
	private PageLayoutComposite pagelayoutComp;

	// Absatzformat
	private ParagraphComposite paragraphComp;

	private PrintProject printProject;

	// Liste auf der linken Spalte
	private List selectList;

	// Composite auf der rechten Spalte
	private Composite setupComp, rightComp;

	private Shell shell;

	public FormatSetup() {
	}

	@Override
	public void notifyObservers() {
		for (IObserverControl o : observerList) {
			o.updateControl();
		}
	}

	public void open() {
		Display display = Display.getDefault();
		shell = new Shell(display, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL
				| SWT.RESIZE | SWT.MAX | SWT.MIN);
		shell.setLayout(new FillLayout());

		ScrolledComposite sc = new ScrolledComposite(shell, SWT.H_SCROLL
				| SWT.V_SCROLL);
		final StackLayout stackLayout = new StackLayout();
		Composite mainComp = new Composite(sc, SWT.NONE);

		if (format != null)
			shell.setText(GuiMessages.Stileditor_Gui_ParameterOf + " \""
					+ format.getName() + "\"");

		mainComp.setLayout(new GridLayout());
		// setMenu();
		SashForm sashForm = new SashForm(mainComp, SWT.BORDER);
		sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));

		// Liste auf der linken Spalte definieren
		selectList = new List(sashForm, SWT.NONE);
		selectList.setItems(new String[] {
				GuiMessages.Stileditor_Gui_InlineFormat,
				GuiMessages.Stileditor_Gui_ParagraphFormat,
				GuiMessages.Stileditor_Gui_FootnoteFormat,
				GuiMessages.Stileditor_Gui_LanguageOptions,
				GuiMessages.Stileditor_Gui_PageLayoutOptions });
		selectList.select(0);

		selectList.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				switch (selectList.getSelectionIndex()) {
				case 0:
					stackLayout.topControl = fontComp.getComp();
					break;
				case 1:
					stackLayout.topControl = paragraphComp.getComp();
					break;
				case 2:
					stackLayout.topControl = footnoteComp.getComp();
					break;
				case 3:
					stackLayout.topControl = languageComp.getComp();
					break;
				case 4:
					stackLayout.topControl = pagelayoutComp.getComp();
					break;
				default:
					// Display display;
					// Shell shell;
					// display = Display.getDefault();
					//
					// shell = new Shell(display, SWT.DIALOG_TRIM
					// | SWT.APPLICATION_MODAL | SWT.RESIZE | SWT.MAX
					// | SWT.MIN);
					// shell.setLayout(new FillLayout());

					/*
					 * _PrintProject_tmp project = new _PrintProject_tmp();
					 * ProjectManager pm = ProjectManager.getInstance();
					 * pm.register(project); pm.setActiveProject(project);
					 * ReferenceFieldGroup group = new ReferenceFieldGroup();
					 * project.setReferenceGroup(group);
					 * 
					 * ReferenceField field = new ReferenceField(); String
					 * xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?>  " +
					 * "<field>   " + "<id>1</id>  " + " <name>Test</name>  " +
					 * " <content>"
					 * +"<select>0</select>"+"<value></value>"+"<xPath>//ab</xPath>"
					 * +"</content>   " + "<counter>     " +
					 * "<select>4</select>     " +
					 * "<attribute>5</attribute>    " +
					 * " <startValue>6</startValue>   " + "  <reset>     " +
					 * "  <select>7</select>     " + "  <name>8</name>   " +
					 * "  <xPath>//Test</xPath> " + "  </reset> " +
					 * "  </counter>  " + " <title>   " +
					 * "  <select>10</select>   " +
					 * "  <attribute>11</attribute> " + "    <xPath>12</xPath> "
					 * + "  </title> " + "</field> ";
					 * 
					 * Document doc = null; try { doc =
					 * DocumentHelper.parseText(xmlStr); } catch
					 * (DocumentException e1) { e1.printStackTrace(); }
					 * 
					 * field.update(doc); group.add(field); ReferenceField
					 * field2 = new ReferenceField(); field2.setValue("name",
					 * "name2"); group.add(field2);
					 * 
					 * ReferenceField field3 = new ReferenceField();
					 * field3.setValue("name", "name3"); group.add(field3);
					 * ReferenceField field4 = new ReferenceField();
					 * field4.setValue("name", "name4"); group.add(field4);
					 * ReferenceField field5 = new ReferenceField();
					 * field5.setValue("name", "name5"); group.add(field5);
					 */
					// ReferenceFieldSetup setup = new
					// ReferenceFieldSetup(shell,
					// SWT.NONE);
					// setup.setInput(referenceFieldGroup, format);
					//
					// shell.layout();
					// FileUtil.shellSetCenter(shell);
					// shell.open();
					// while (!shell.isDisposed()) {
					// if (!display.readAndDispatch()) {
					// display.sleep();
					// }
					// }
					// shell.dispose();

				}
				setupComp.layout();//
			}
		});

		// Container fuer fonComp und msComp
		rightComp = new Composite(sashForm, SWT.NONE);
		rightComp.setLayout(new GridLayout());

		setupComp = new Composite(rightComp, SWT.NONE);
		setupComp.setLayoutData(new GridData(GridData.FILL_BOTH));
		setupComp.setLayout(stackLayout);

		Composite footComp = new Composite(mainComp, SWT.NONE);
		footComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		footComp.setLayout(new GridLayout(2, true));

		Composite blockInlineComp = new Composite(footComp, SWT.NONE);
		blockInlineComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		blockInlineComp.setLayout(new GridLayout(4, false));

		fontComp = new FontComposite(setupComp, 0, format);
		paragraphComp = new ParagraphComposite(setupComp, 0, format);
		footnoteComp = new FootnoteComposite(setupComp, 0, format);
		footnoteComp.setPrintProject(printProject);
		languageComp = new LanguageComposite(setupComp, 0, format);
		pagelayoutComp = new PageLayoutComposite(setupComp, 0, format);

		inlineRadio = new Button(blockInlineComp, SWT.RADIO);
		inlineRadio.setText(GuiMessages.General_Gui_Inline);
		inlineRadio.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				if (!inlineRadio.getSelection())
					return;
				footnoteComp.setEnabled(false);
			}

		});

		blockRadio = new Button(blockInlineComp, SWT.RADIO);
		blockRadio.setText(GuiMessages.General_Gui_Block);
		blockRadio.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				if (!blockRadio.getSelection())
					return;
				footnoteComp.setEnabled(false);
			}

		});

		footnoteRadio = new Button(blockInlineComp, SWT.RADIO);
		footnoteRadio.setText(GuiMessages.General_Gui_Footnote);
		footnoteRadio.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				if (!footnoteRadio.getSelection())
					return;
				footnoteComp.setEnabled(true);
				selectList.select(2);
				stackLayout.topControl = footnoteComp.getComp();
				setupComp.layout();
			}

		});

		stackLayout.topControl = fontComp.getComp();
		sashForm.setWeights(new int[] { 1, 4 });

		// Fo Category feststehen: inline/block/footnote
		if (format.getFoCategory().equals("inline")) {
			inlineRadio.setSelection(true);
		} else if (format.getFoCategory().equals("footnote")) {
			footnoteRadio.setSelection(true);
		} else if (format.getFoCategory().equals("block")) {
			blockRadio.setSelection(true);
		}
		// bei standard muss footnoteRadio deaktiviert werden
		if (format.getType().equals("standard"))
			footnoteRadio.setEnabled(false);

		Composite buttonComp = new Composite(footComp, SWT.NONE);
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.END;
		buttonComp.setLayoutData(gridData);

		RowLayout rowLayout = new RowLayout();
		rowLayout.pack = false;
		rowLayout.spacing = 15;
		buttonComp.setLayout(rowLayout);

		// save
		Button okButton = new Button(buttonComp, SWT.NONE);
		okButton.setText(GuiMessages.General_Gui_Okay);
		okButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				if (!fontComp.controlValueVertify()
						|| !paragraphComp.controlValueVertify()
						|| !footnoteComp.controlValueVertify()
						|| !languageComp.controlValueVertify()
						|| !pagelayoutComp.controlValueVertify())
					return;

				format = fontComp.getFormat();
				format = paragraphComp.getFormat();
				format = footnoteComp.getFormat();
				format = languageComp.getFormat();
				format = pagelayoutComp.getFormat();

				if (blockRadio.getSelection())
					format.setFoCategory("block");
				else if (inlineRadio.getSelection())
					format.setFoCategory("inline");
				else if (footnoteRadio.getSelection()) {
					format.setFoCategory("footnote");
				}
				shell.dispose();
			}
		});

		Button cancelButton = new Button(buttonComp, SWT.NONE);
		cancelButton.setText(GuiMessages.General_Gui_Cancel);
		cancelButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				shell.dispose();
			}
		});

		footComp.pack();

		sc.setExpandHorizontal(true);
		sc.setExpandVertical(true);
		sc.setContent(mainComp);
		mainComp.pack();

		shell.pack();
		sc.setMinSize(mainComp.getSize());
		FileUtil.shellSetCenter(shell);
		shell.open();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		shell.dispose();
	}

	@Override
	public void registerObserver(IObserverControl observer) {
		observerList.add(observer);
	}

	@Override
	public void removeObserver(IObserverControl observer) {
		observerList.remove(observer);
	}

	public void setInput(PrintProject pProject, Format format) {
		this.format = format;
		printProject = pProject;
	}

}
